import { Provide,Inject } from '@midwayjs/core';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { user } from '../entity/user.entity';
import { UserDto,UpdateUserDto } from '../dto/userDto';
import { UserDao } from '../dao/user.dao';
import * as bcrypt from 'bcryptjs';
@Provide()

export class UserService {
    
    @InjectEntityModel(user)
    userModel: Repository<user>;

    @Inject()
    userDao: UserDao;
//使用id查找
    async getUserInfo(user_id: UserDto['user_id']){
        return await this.userDao.getUser(user_id);
    }
//使用account查找
    async getUserByAccount(account: UserDto['account']) {
        return await this.userDao.getUserByAccount(account);
    }
//查找信息
    async isWgj(userId: UserDto['user_id']) {
        return await this.userDao.isWgj(userId);
    }
//更新信息
    async updateUser(userId: UpdateUserDto['user_id'], userData: UpdateUserDto) {

        //获取当前用户更改前的信息
        const currentUser = await this.userDao.getUser(userId);

        //筛选出不为空的字段
        const updatedUser = Object.keys(userData).reduce((acc,key)=>{
            if(userData[key]!==null||userData[key]!==undefined){
                acc[key]=userData[key];
            }
            return acc;
        },{} as UpdateUserDto);

        //过滤没有修改的值
        for(const key in updatedUser){
            if(updatedUser[key]===currentUser[key]||await bcrypt.compare(updatedUser[key],currentUser[key])){
                throw new Error(`${key}未修改`);
            }
        }

        //传入密码则加密
        if (updatedUser.password){
            updatedUser.password = await bcrypt.hash(updatedUser.password, 10);
        }

        //转发到下一层
        return await this.userDao.updateUser(userId, updatedUser);
    }

}